package com.walkline.screen;

import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;

import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.GaugeField;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.music.MusicPlayer;
import com.walkline.music.MusicSDK;
import com.walkline.music.inf.Playlist;
import com.walkline.music.inf.Tracks;
import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Enumerations.Toplists;
import com.walkline.util.Function;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;
import com.walkline.util.ui.VerticalButtonFieldSet;

public final class ToplistScreen extends MainScreen implements PlayerListener
{
	ForegroundManager _foreground = new ForegroundManager(0);
	ListStyleButtonSet _songsSet = new ListStyleButtonSet();
	ListStyleButtonField _item;
	MusicSDK _music;
	MusicPlayer _player;
	int _category;
	boolean _playAllMusic = true;
	Thread _thread = null;
	GaugeField _progress;
	int _duration = 0;

    public ToplistScreen(MusicSDK music, MusicPlayer player, int category)
    {
    	super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

        setTitle(Toplists.categories[category]);

        _music = music;
        _player = player;
        _player.setPlayerListener(this);
        _category = category;
        add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run() {getPlaylist();}
		});
    }

	private void getPlaylist()
	{
		RefreshContentsScreen popupScreen = new RefreshContentsScreen(_music, _category, RefreshActions.PLAYLIST);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Playlist playlist = popupScreen.getPlaylist();

		if (popupScreen != null) {popupScreen = null;}
		if (playlist != null) {refreshPlaylist(playlist);}
	}

	private void refreshPlaylist(Playlist list)
	{
		Tracks[] songsList = list.getSongsList();
		Tracks song;

		if (songsList.length <= 0) {return;}

		if (_songsSet.getManager() == null) {_foreground.add(_songsSet);}
		if (_songsSet.getFieldCount() > 0) {_songsSet.deleteAll();}

		for (int i=0; i<30; i++)
		{
			song = songsList[i];
			if (song != null)
			{
				_item = new ListStyleButtonField(song);
				_item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC)
						{
							
						}
					}
				});
				_songsSet.add(_item);
			}
		}
	}

	private void preparePlayMusic(int playlistIndex)
	{
		ListStyleButtonField item = (ListStyleButtonField) _songsSet.getFieldWithFocus();
		VerticalButtonFieldSet viewVendorSet=new VerticalButtonFieldSet(USE_ALL_WIDTH);
		_progress = new GaugeField("", 0, 100, 0, GaugeField.PERCENT | GaugeField.NO_TEXT);
    	viewVendorSet.setMargin(0,0,0,0);
    	viewVendorSet.add(_progress);
    	_songsSet.insert(viewVendorSet, _songsSet.getFieldWithFocusIndex() + 1);
    	_duration = item.getDuration();
		_player.play(item.getMp3Url());

		ListStyleButtonField item = (ListStyleButtonField) _songsSet.getField(currentIndex + 1);
		VerticalButtonFieldSet viewVendorSet=new VerticalButtonFieldSet(USE_ALL_WIDTH);
		_progress = new GaugeField("", 0, 100, 0, GaugeField.PERCENT | GaugeField.NO_TEXT);
    	viewVendorSet.setMargin(0,0,0,0);
    	viewVendorSet.add(_progress);
    	item.setFocus();
    	_songsSet.insert(viewVendorSet, _songsSet.getFieldWithFocusIndex() + 1);
    	_duration = item.getDuration();
		_player.play(item.getMp3Url());
	}

	protected boolean keyChar(char key, int status, int time)
    {
		if (getFieldWithFocus() instanceof ForegroundManager)
		{
			switch (key)
			{
    			case Characters.SPACE:
    				_player.pause();
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_A:
    			case Characters.LATIN_SMALL_LETTER_A:
    				_playAllMusic = !_playAllMusic;

    				Function.infoDialog("顺序播放已 " + (_playAllMusic ? "打开" : "关闭"));
    				return true;
    			case Characters.LATIN_CAPITAL_LETTER_S:
    			case Characters.LATIN_SMALL_LETTER_S:
    				int currentTime = (int) (_player.getMediaTime() / 1000);
					int progress = (int) (((float) currentTime) / (((float)_duration)) * 100);
    				Function.errorDialog(_player.getStatus() + "\n当前时间: " + currentTime + "\n总时长: " + _duration + "\n当前进度: " + progress);
    				return true;
			}
		}

    	return super.keyChar(key, status, time);
    }

	protected boolean onSavePrompt() {return true;}

	class PlayerProgressRunnable implements Runnable
	{
		public void run()
		{
			while (true)
			{
				if (_player.getMediaTime() == 0)
				{
					try {
						_thread.interrupt();
						_thread = null;
					} catch (Exception e) {}
				} else {
					int currentTime = (int) (_player.getMediaTime() / 1000);
					int progress = (int) (((float) currentTime) / (((float)_duration)) * 100);
					_progress.setValue(progress); //_player.getMediaTimePercent());
				}

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {}
			}
		}
	}

	public void playerUpdate(Player player, String event, Object eventData)
	{
		if (event == PlayerListener.END_OF_MEDIA)
		{
			if (_thread != null)
			{
				try {
					_thread.interrupt();
					_thread = null;
				} catch (Exception e) {}
			}

			for (int i=0; i<_songsSet.getFieldCount(); i++)
			{
				//Function.errorDialog(_songsSet.getField(i).getClass().getName());
				if (_songsSet.getField(i) instanceof VerticalButtonFieldSet)
				{
					synchronized (Application.getEventLock())
					{
						_songsSet.delete(_songsSet.getField(i));
					}
					break;
				}
			}

			if (_playAllMusic)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run()
					{
						int currentIndex = _songsSet.getFieldWithFocusIndex();
						if (currentIndex < _songsSet.getFieldCount())
						{
							preparePlayMusic();
						}
					}
				});
			}
		} else if (event == PlayerListener.STARTED) {
			_thread = new Thread(new PlayerProgressRunnable());

			_thread.start();
		}
	}
}